package com.xiao.framework.ds.autoconfigure.aspectj;

import com.xiao.framework.ds.annotation.Database;
import com.xiao.framework.ds.autoconfigure.MultiDataSourceClassResolver;
import com.xiao.framework.ds.autoconfigure.context.DataSourceHolder;
import java.lang.reflect.Method;
import java.util.Optional;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * @author <a href="mailto:xiaoquanidea@163.com">hutiquan</a>
 * @since 2019-08-24 13:08
 */
public class MultiDataSourceInterceptor implements MethodInterceptor, Ordered {

  private MultiDataSourceClassResolver resolver = new MultiDataSourceClassResolver();

  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
      before(invocation);
      return invocation.proceed();
    } finally {
      after();
    }
  }

  private void before(MethodInvocation invocation) throws IllegalAccessException {
    Method method = invocation.getMethod();
    Class<?> targetClass = resolver.targetClass(invocation);
    Database dataBase = method.isAnnotationPresent(Database.class) ? method.getAnnotation(Database.class):
        AnnotationUtils.findAnnotation(targetClass, Database.class);
    Optional.ofNullable(dataBase).ifPresent(ds -> DataSourceHolder.push(ds.value()));

  }

  private void after() {
    DataSourceHolder.pop();
  }

  @Override
  public int getOrder() {
    return HIGHEST_PRECEDENCE;
  }
}
